# Simple ASCII-only convolution explanation
import numpy as np
import matplotlib.pyplot as plt

def main():
    print("CONVOLUTION FORMULA EXPLANATION")
    print("="*50)
    print("\nConvolution formula: (f * g)(t) = Integral[f(tau) * g(t-tau)] dtau from -infinity to +infinity")
    
    # Explain each part
    print("\nPARTS OF THE FORMULA:")
    print("1. (f * g)(t): Convolution result at time t")
    print("2. f(tau): First function at time tau")
    print("3. g(t-tau): Second function shifted by t, reversed")
    print("4. Integral: Sum of all products")
    
    # Explain steps
    print("\nFOUR STEPS OF CONVOLUTION:")
    print("1. FLIP: Reverse g(tau) to get g(-tau)")
    print("2. SHIFT: Shift reversed g by t to get g(t-tau)")
    print("3. MULTIPLY: Multiply f(tau) with g(t-tau)")
    print("4. INTEGRATE: Calculate area under the product curve")
    
    # Create simple visualization
    create_basic_visualization()
    
    print("\nVisualization saved as 'convolution_simple.png'")

def create_basic_visualization():
    # Create figure with 4 subplots
    fig, axs = plt.subplots(4, 1, figsize=(10, 12))
    
    # Time axis
    t = np.linspace(-2, 4, 500)
    
    # Define simple functions
    def f(t_val):
        return np.where((t_val >= 0) & (t_val <= 1), 1, 0)
    
    def g(t_val):
        return np.where((t_val >= 0) & (t_val <= 1), 1, 0)
    
    # Step 1: Original functions
    axs[0].plot(t, f(t), 'b-', linewidth=2, label='f(tau)')
    axs[0].plot(t, g(t), 'r-', linewidth=2, label='g(tau)')
    axs[0].set_title('STEP 1: Original Functions', fontsize=14)
    axs[0].set_xlabel('tau')
    axs[0].set_ylabel('Amplitude')
    axs[0].legend()
    axs[0].grid(True)
    axs[0].set_xlim(-2, 4)
    axs[0].set_ylim(-0.2, 1.5)
    
    # Step 2: Reversed g
    axs[1].plot(t, g(-t), 'g-', linewidth=2, label='g(-tau)')
    axs[1].plot(t, g(t), 'r--', linewidth=1, label='g(tau) (original)')
    axs[1].set_title('STEP 2: Reverse g(tau) to g(-tau)', fontsize=14)
    axs[1].set_xlabel('tau')
    axs[1].set_ylabel('Amplitude')
    axs[1].legend()
    axs[1].grid(True)
    axs[1].set_xlim(-2, 4)
    axs[1].set_ylim(-0.2, 1.5)
    
    # Step 3: Shifted g and product with f (t=1)
    t_shift = 1.0
    axs[2].plot(t, f(t), 'b-', linewidth=2, label='f(tau)')
    axs[2].plot(t, g(t_shift - t), 'g-', linewidth=2, label='g(1-tau)')
    
    # Product
    product = f(t) * g(t_shift - t)
    axs[2].fill_between(t, 0, product, color='gray', alpha=0.3, label='Product')
    
    axs[2].set_title('STEP 3: Shift and Multiply (t=1)', fontsize=14)
    axs[2].set_xlabel('tau')
    axs[2].set_ylabel('Amplitude')
    axs[2].legend()
    axs[2].grid(True)
    axs[2].set_xlim(-2, 4)
    axs[2].set_ylim(-0.2, 1.5)
    
    # Step 4: Convolution result
    t_conv = np.linspace(-2, 4, 500)
    conv_result = np.convolve(f(t), g(t), mode='same')
    conv_result = conv_result * (t[1] - t[0])  # Normalize
    
    axs[3].plot(t_conv, conv_result, 'm-', linewidth=2, label='(f * g)(t)')
    axs[3].axvline(x=t_shift, color='orange', linestyle='--', alpha=0.7)
    
    # Mark value at t=1
    idx = np.argmin(np.abs(t_conv - t_shift))
    axs[3].plot(t_shift, conv_result[idx], 'ro', markersize=8)
    axs[3].text(t_shift+0.1, conv_result[idx], f'Value: {conv_result[idx]:.2f}', fontsize=10)
    
    axs[3].set_title('STEP 4: Convolution Result', fontsize=14)
    axs[3].set_xlabel('t')
    axs[3].set_ylabel('(f * g)(t)')
    axs[3].legend()
    axs[3].grid(True)
    axs[3].set_xlim(-2, 4)
    axs[3].set_ylim(-0.2, 1.5)
    
    # Add formula text
    fig.text(0.5, 0.01, 'Convolution Formula: (f * g)(t) = Integral[f(tau) * g(t-tau)] dtau', 
             ha='center', fontsize=12, bbox=dict(facecolor='lightyellow', alpha=0.5))
    
    plt.tight_layout(rect=[0, 0.03, 1, 0.97])
    plt.savefig('convolution_simple.png', dpi=300)
    plt.close()

if __name__ == "__main__":
    main()